package com.bianguo.android.bprinter.view.activity;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.Toast;

import com.bianguo.android.baselibrary.utils.MLog;
import com.bianguo.android.baselibrary.view.BaseActivity;
import com.bianguo.android.bprinter.R;
import com.bianguo.android.ioclibrary.annotations.BindView;
import com.bianguo.android.ioclibrary.annotations.OnClick;

import java.lang.ref.WeakReference;
import java.net.URI;

public class WebActivity extends BaseActivity {

    @BindView(R.id.web_view)
    WebView mWebView;
    @BindView(R.id.web_image)
    ImageView webImg;
    @BindView(R.id.web_scroll_view)
    ScrollView mScrollView;

    private final String URL = "https://www.baidu.com";
    private WebSettings mWebSettings;
    private static OvertimeHandler mHandler;

    @Override
    protected int layoutId() {
        return R.layout.activity_web;
    }

    @Override
    protected void initView(@Nullable Bundle savedInstanceState) {
        mWebSettings = mWebView.getSettings();
        mWebSettings.setJavaScriptEnabled(true);
        mWebSettings.setSupportZoom(true);
        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                view.loadUrl(request.getUrl().toString());
                return true;
            }

            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                super.onReceivedError(view, request, error);
                MLog.mLog("onReceivedError error = " + error.toString() + ", " + error.getDescription());
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                MLog.mLog("onPageStarted url = " + url);
                if (mHandler == null) {
                    mHandler = new OvertimeHandler(WebActivity.this);
                }
                mHandler.sendEmptyMessageDelayed(0, 5000);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                MLog.mLog("onPageFinished url = " + url);
                if (mHandler != null) {
                    mHandler.removeMessages(0);
                }
            }

            @Override
            public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
                super.onReceivedHttpError(view, request, errorResponse);
                MLog.mLog("onReceivedHttpError error = " + errorResponse.toString());
            }
        });

        mWebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                MLog.mLog("onReceivedTitle title = " + title);
            }

            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                MLog.mLog("newProgress = " + newProgress);
                if (newProgress >= 100 && mHandler != null) {
                    mHandler.removeMessages(0);
                }
            }
        });
        mWebView.loadUrl(URL);
    }

    @OnClick({R.id.web_screen_btn})
    public void onClickBk(View view) {
        switch (view.getId()) {
            case R.id.web_screen_btn:
                Bitmap bitmap = getViewBitmap(mWebView);
                mWebView.setVisibility(View.GONE);
                mScrollView.setVisibility(View.VISIBLE);

                DisplayMetrics dm = new DisplayMetrics();
                getWindowManager().getDefaultDisplay().getMetrics(dm);
                int screenHeight = dm.heightPixels;
                if (bitmap.getHeight() <= screenHeight) {
                    webImg.setImageBitmap(bitmap);
                } else {
                    Bitmap bmp = Bitmap.createScaledBitmap(bitmap, bitmap.getWidth(), screenHeight,  true);
                    webImg.setImageBitmap(bmp);
                }
                break;
        }
    }

    private Bitmap getViewBitmap(WebView webView) {
        int height = (int) (webView.getContentHeight() * webView.getScale());
        int width = webView.getWidth();
        int pH = webView.getHeight();
        Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
        Canvas canvas = new Canvas(bm);
        int top = height;
        while (top > 0) {
            if (top < pH) {
                top = 0;
            } else {
                top -= pH;
            }
            canvas.save();
            canvas.clipRect(0, top, width, top + pH);
            webView.scrollTo(0, top);
            webView.draw(canvas);
            canvas.restore();
        }
        return bm;
    }

    private static class OvertimeHandler extends Handler {

        private final WeakReference<WebActivity> mReferences;

        public OvertimeHandler(WebActivity activity) {
            mReferences = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    Toast.makeText(mReferences.get(), "网络异常，请检查网络", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    }
}
